﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ModifyMimeTypes
{
    public partial class EditTypeForm : Form
    {
        public EditTypeForm(string mimeType)
        {
            InitializeComponent();

            //Set our text boxes to the passed in mime type (will be empty for "New")
            txtOriginal.Text = mimeType;
            txtNew.Text = mimeType;

            //Change the form name if this is a "new" operation
            if (mimeType == "")
            {
                this.Text = "New Mime Type";
            }
        }

        //Returns the new Mime Type that was set, if any
        //Used by the parent form to detect modifications
        public string MimeType
        {
            get { return txtNew.Text; }
        }

        //Validates the value currently in txtNew.Text
        public bool ValidateMimeType()
        {
            bool valid = false;

            int slashCount = txtNew.Text.Split('/').Length - 1;
            int semiCount = txtNew.Text.Split(';').Length - 1;

            if (slashCount == 1 && semiCount == 1
                && !txtNew.Text.Contains(' ')
                && txtNew.Text.LastIndexOf('/') != txtNew.Text.Length - 1
                && txtNew.Text.LastIndexOf(';') != txtNew.Text.Length - 1
                && txtNew.Text.IndexOf('/') != 0
                && txtNew.Text.IndexOf(';') != 0
                && txtNew.Text.IndexOf('/') < txtNew.Text.IndexOf(';'))
            {
                valid = true;
            }

            return valid;
        }

        //Handles clicking of all buttons on the screen
        private void btnClick(object sender, EventArgs e)
        {
            switch (((Button)sender).Name)
            {
                case "btnSave":
                    {
                        //Make sure the mime type checks out
                        if (ValidateMimeType())
                        {
                            this.Close(); //Close the form
                        }
                        else
                        {
                            MessageBox.Show("The string must contain a single /, and single ;, and no spaces.", "Invalid string");
                        }
                    }

                    break;

                case "btnCancel":
                    {
                        //Revert any changes to the txtNew box so that the parent
                        //form doesn't grab them
                        txtNew.Text = "";

                        this.Close(); //Close the form
                    }

                    break;
            }
        }
    }
}
